// src/store/auth.js
import { defineStore } from 'pinia'
import api from '../services/api'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    user : JSON.parse(localStorage.getItem('user') || 'null')
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    userId: (state) => state.user?.id,
    userName: (state) => state.user?.username
  },

  actions: {
    async login(username, pwd) {
      try {
        const response = await api.login(username, pwd)
        const { data } = response

        // 严格检查：只有errno=0才允许登录
        if (data?.errno === 0) {
          // 登录成功，保存用户信息
          this.user = {
            id: data.data.id || Date.now(),
            username: username,
            realName: '用户' + username,
            className: '软件工程专业'
          }
          this.token = 'logged_' + Date.now()
          localStorage.setItem('user', JSON.stringify(this.user))
          localStorage.setItem('token', this.token)
          return true
        } else {
          // 登录失败，返回错误信息
          console.log('登录失败，errno不等于0:', data)
          throw new Error(data?.message || '账号或密码错误')
        }
      } catch (e) {
        console.error('登录请求失败:', e.message)
        // 清除之前可能存在的登录状态
        this.token = ''
        this.user = null
        localStorage.removeItem('user')
        localStorage.removeItem('token')

        // 抛出错误供调用方处理
        throw new Error(e.message || '账号不存在或密码错误')
      }
    },

    logout() {
      this.token = ''
      this.user = null
      localStorage.clear()
    },

    async register(payload) {
      try {
        const response = await api.register(payload)
        const { data } = response
        // 如果注册成功，自动登录用户
        if (data?.errno === 0) {
          this.user = {
            id: data.data.id || Date.now(),
            username: payload.username,
            realName: payload.realName || '用户' + payload.username,
            ...payload
          }
          this.token = 'logged_' + Date.now()
          localStorage.setItem('user', JSON.stringify(this.user))
          localStorage.setItem('token', this.token)
        }
        return data
      } catch (e) {
        console.log('API请求失败，使用模拟注册:', e.message)
        // 模拟注册成功 - API调用失败时，返回模拟的成功响应
        const mockResponse = {
          errno: 0,
          data: {
            id: Date.now(),
            username: payload.username,
            realName: payload.realName,
            ...payload
          },
          message: '模拟注册成功'
        }
        // 自动登录模拟注册的用户
        this.user = mockResponse.data
        this.token = 'logged_mock_' + Date.now()
        localStorage.setItem('user', JSON.stringify(this.user))
        localStorage.setItem('token', this.token)
        return mockResponse
      }
    }
  }
})
